﻿using HPIT.RentHouse.Common;
using HPIT.RentHouse.DTO;
using HPIT.RentHouse.IService;
using HPIT.RentHouse.Service.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HPIT.RentHouse.Service
{
    public class RolesService : IRolesService
    {
        public RoleEditDTO Get(long id)
        {
            using (var db = new RentHouseEntities())
            {
                var roleService = new BaseService<T_Roles>(db);
                //1、获取数据库中的该角色信息
                T_Roles role = roleService.Get(e => e.Id == id);
                //2、实例化dto模型并赋值（id，name）
                var dto = new RoleEditDTO();
                dto.Id = role.Id;
                dto.Name = role.Name;
                dto.PermissionIds = role.T_Permissions.Select(a => a.Id).ToList();
                return dto;
            }
        }

        public List<RoleDTO> GetList()
        {
            using (var db = new RentHouseEntities())
            {
                var bs = new BaseService<T_Roles>(db);
                var list = bs.GetList(e => true).Select(e => new RoleDTO
                {
                    Id = e.Id,
                    Name = e.Name
                }).ToList(); ;
                return list;
            }
        }

        public List<RoleDTO> GetPageList(int start, int length, string name, ref int rowCount)
        {
            using (var db = new RentHouseEntities())
            {
                var bs = new BaseService<T_Roles>(db);
                var query = PredicateExtensions.True<T_Roles>();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    query = query.And(e => e.Name.Contains(name));
                }
                var list = bs.GetPagedList(start, length, ref rowCount, query, e => e.Id, false).Select(e => new RoleDTO
                {
                    Id = e.Id,
                    Name = e.Name
                }).ToList(); ;
                return list;
            }
        }

        public AjaxResult Add(RoleEditDTO dto)
        {
            //1、角色表添加  
            var db = new RentHouseEntities();
            var bs = new BaseService<T_Roles>(db);
            var bsp = new BaseService<T_Permissions>(db);

            var model = new T_Roles();
            model.Name = dto.Name;
            model.CreateDateTime = DateTime.Now;

            //2、关联表角色权限的添加
            if(dto.PermissionIds!=null&& dto.PermissionIds.Count > 0)
            {
                foreach(var id in dto.PermissionIds)
                {
                    T_Permissions per = bsp.Get(a => a.Id == id);
                    model.T_Permissions.Add(per);
                }
            }

           
            long roleId = bs.Add(model);
            if (roleId > 0)
            {
                return new AjaxResult(ResultState.Success, "添加角色成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "添加角色失败");
            }
        }

        public AjaxResult Update(RoleEditDTO dto)
        {
            var db = new RentHouseEntities();
            var bs = new BaseService<T_Roles>(db);
            var bsp = new BaseService<T_Permissions>(db);
            //1、修改角色
            var model = bs.Get(e => e.Id == dto.Id);
            model.Name = dto.Name;

            //2、修改角色的权限（先删除，然后再添加数组里的权限id）
            model.T_Permissions.Clear();

            if (dto.PermissionIds != null && dto.PermissionIds.Count > 0)
            {
                foreach (var id in dto.PermissionIds)
                {
                    T_Permissions per = bsp.Get(a => a.Id == id);
                    model.T_Permissions.Add(per);
                }
            }


            if (bs.Update(model))
            {
                return new AjaxResult(ResultState.Success, "修改角色成功");
            }
            else
            {
                return new AjaxResult(ResultState.Error, "修改角色失败");
            }
        }

        public AjaxResult Delete(long id)
        {
            var db = new RentHouseEntities();
            BaseService<T_Roles> bs = new BaseService<T_Roles>(db);
            var model = bs.Get(e => e.Id == id);
            if (model == null)
            {
                return new AjaxResult(ResultState.Error, "角色不存在");
            }
            else
            {
                //1、删除角色对应的权限
                model.T_Permissions.Clear();
                //2、删除角色
                if (bs.Delete(model))
                {
                    return new AjaxResult(ResultState.Success, "删除角色成功");
                }
                else
                {
                    return new AjaxResult(ResultState.Error, "删除角色失败");
                }

            }
          
        }

        /// <summary>
        /// 批量删除权限
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public AjaxResult DeleteBatch(List<long> ids)
        {
            try
            {
                var db = new RentHouseEntities();
                BaseService<T_Roles> bs = new BaseService<T_Roles>(db);
                foreach (var id in ids)
                {
                    var model = bs.Get(e => e.Id == id);
                    //1、删除角色对应的权限
                    model.T_Permissions.Clear();
                    //2、删除角色
                    bs.Delete(model);
                }
                return new AjaxResult(ResultState.Success, "删除成功");
            }
            catch (Exception)
            {
                return new AjaxResult(ResultState.Error, "删除失败");
            }
        }
    }
}
